package com.example.pt.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.pt.entity.UserTransferStats;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Mapper
public interface UserTransferStatsMapper extends BaseMapper<UserTransferStats> {
    //根据异常种子找到
//    userId：用户 ID
//    fileSize：种子文件大小
//    downloaded：该用户对该种子的总下载量
//    uploaded：该用户对该种子的总上传量
// Mapper 接口（已正确使用 @Param 注解）
    @Select({
            "SELECT ",
            "uts.user_id AS userId, ",
            "tf.file_size AS fileSize, ",
            "uss.start_time AS startTime, ",
            "uss.last_active_time AS lastActiveTime, ",
            "uss.seed_days AS seedDays, ",
            "SUM(uts.downloaded) AS downloaded, ",
            "SUM(uts.uploaded) AS uploaded, ",
            "u.level AS level ",
            "FROM user_transfer_stats uts ",
            "JOIN torrent_info_hash tih ON uts.info_hash = tih.info_hash ",
            "JOIN torrentFile tf ON tih.tid = tf.tid ",
            "LEFT JOIN user_seed_stats uss ON uts.user_id = uss.user_id AND tih.info_hash = uss.info_hash ",
            "JOIN user u ON uts.user_id = u.uid ",
            "WHERE tih.tid = #{tid}",
//            "AND (uss.start_time IS NULL OR TIMESTAMPDIFF(HOUR, uss.start_time, NOW()) > 24) ",
            "GROUP BY uts.user_id, tih.info_hash"
    })
    List<Map<String, Object>> findUserStatsByAbnormalTorrents(
            @Param("tid") Integer abnormalTorrentIds);

    //得到每个种子的总上传量和下载量
    @Select({
            "SELECT ",
            "tf.tid AS tid, ",
            "SUM(uts.downloaded) AS totalDownloaded, ", // 总下载量
            "SUM(uts.uploaded) AS totalUploaded ", // 总上传量
            "FROM user_transfer_stats uts ",
            "JOIN torrent_info_hash tih ON uts.info_hash = tih.info_hash ",
            "JOIN torrentFile tf ON tih.tid = tf.tid ",
            "GROUP BY tf.tid" // 按种子 ID 分组
    })
    List<Map<String, Object>> calculateStatsByTorrent();

    /**
     * 获取用户的总上传量、总下载量、总虚拟上传量和总虚拟下载量
     * @param userId 用户ID
     * @return 包含总上传量、总下载量、总虚拟上传量和总虚拟下载量的Map
     */
    @Select("SELECT " +
            "COALESCE(SUM(uploaded), 0) as totalUploaded, " +
            "COALESCE(SUM(downloaded), 0) as totalDownloaded, " +
            "COALESCE(SUM(virtual_uploaded), 0) as totalVirtualUploaded, " +
            "COALESCE(SUM(virtual_downloaded), 0) as totalVirtualDownloaded " +
            "FROM user_transfer_stats " +
            "WHERE user_id = #{userId}")
    Map<String, Object> getUserTotalTransferStats(@Param("userId") Integer userId);
} 